package com.lhb.boyixue.user.interceptor;


import com.lhb.boyixue.base.BaseContext;
import com.lhb.boyixue.base.JwtConfig;
import com.lhb.boyixue.base.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 86131
 * @version 1.0
 * @description 令牌统一校验拦截器
 * @date 2025/4/24 下午7:47
 */
@Component
public class UserJwtTokenHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    JwtConfig jwtConfig;
    @Autowired
    JwtUtil jwtUtil;
    /**
     * 校验jwt
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String authHeader = request.getHeader("Authorization"); // 获取 Authorization 头
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7); // 去掉 "Bearer " 前缀

            if (jwtUtil.verify(token)) {
                String userId = jwtUtil.getUserId(token);
                BaseContext.setUserId(Long.valueOf(userId));
                return true;
            }
        }
        response.setStatus(401);
        return false;


    }
}
